﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightGolf.Core;
using System.Collections.Generic;

namespace SilverlightGolf.Physics
{
    public class Body
    {
        public Vector2 Position { get; set; }
        public Vector2 Velocity { get; set; }
        public float Mass { get; set; }
        public float Rotation { get; set; }

        public IList<Func<Body, double, Vector2>> DynamicForces { get; private set; }
        public IList<Func<Body, double, double>> ResistiveForces { get; private set; }
        private Vector2 currentImpulse;

        public Body()
        {
            Position = Vector2.Zero;
            Velocity = Vector2.Zero;
            Mass = 1f;
            Rotation = 0f;
            DynamicForces = new List<Func<Body, double, Vector2>>();
            ResistiveForces = new List<Func<Body, double, double>>();
        }

        public void Update(double dt)
        {
            Velocity += currentImpulse / Mass;
            currentImpulse = Vector2.Zero;

            var forceTotal = new Vector2();
            foreach (var force in DynamicForces)
            {
                forceTotal += force(this, dt);
            }

            Velocity += forceTotal * dt / Mass;

            foreach (var force in ResistiveForces)
            {
                Velocity = Velocity.ReduceLength(force(this, dt) * dt / Mass);
            }

            Position += Velocity * dt;
        }

        public void ApplyImpulse(Vector2 impulse)
        {
            currentImpulse += impulse;
        }
    }
}
